package com.whimscrew.oauth.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;

import java.util.Arrays;

/**
 * 授权配置
 */
@Configuration
public class JWTTokenStoreOAuth2Config extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserDetailsService userDetailsService;

    /**
     * 控制客户端可进行的操作
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        String user = "testuser";
        String secret = "thisissecret";
        //保存在内存的方式
        clients.inMemory()
                //验证身份需要提供的用户名称和密钥
                .withClient(user) .secret(secret)
                //支持的授权类型：密码、客户端凭据
                .authorizedGrantTypes("refresh_token", "password", "client_credentials")
                //授权范围：web客户端、移动设备客户端
                .scopes("webclient", "mobileclient");
    }


    @Override
    public void configure(  AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        TokenEnhancerChain tokenEnhancerChain = new TokenEnhancerChain();
        tokenEnhancerChain.setTokenEnhancers( Arrays.asList(tokenEnhancer(), jwtAccessTokenConverter()));
        endpoints.userDetailsService(userDetailsService)
                .authenticationManager(authenticationManager)
                .tokenStore(tokenStore())
                .tokenEnhancer(tokenEnhancerChain) ;
    }




    /**
     * 密码不加密需要加上这个，不然会造成无法获取权限
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }


    @Bean
    public TokenStore tokenStore() {
        return new JwtTokenStore(jwtAccessTokenConverter());
    }

    @Bean
    @Primary //@Primary注解用于告诉Spring，如果有多个特定类型的bean（在本例中是DefaultTokenService），那么就使用被@Primary标注的bean类型进行自动注入
    public DefaultTokenServices tokenServices() {
        //用于从出示给服务的令牌中读取数据
        DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore());
        defaultTokenServices.setSupportRefreshToken(true);
        return defaultTokenServices;
    }


    @Bean
    public JwtAccessTokenConverter jwtAccessTokenConverter() {
        //在JWT和OAuth2服务器之间充当翻译
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        //定义将用于签署令牌的签名密钥
        converter.setSigningKey("copycatinthehouse");
        return converter;
    }

    //自定义token属性
    @Bean
    public TokenEnhancer tokenEnhancer() {
        return new CustomTokenEnhancer();
    }


}
